package com.example.javamaday.leetcode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LeetCodeTest0015 {

    public static void main(String[] args) {

    }

    // 先排序，然后左右指针 夹逼
    public List<List<Integer>> threeSum(int[] nums) {
        // 不够三个数，直接返回
        if (nums.length < 3) {
            return new ArrayList<>();
        }
        Arrays.sort(nums);
        // 判断边际数据，减少操作
        if (nums[0] > 0 || nums[nums.length - 1] < 0) {
            return new ArrayList<>();
        }
        List<List<Integer>> result = new ArrayList<>();
        // 开始
        for (int i = 0; i < nums.length - 2; i++) {
            if (i == 0 || (i > 0 && nums[i] != nums[i - 1])) {
                int lo = i + 1;
                int hi = nums.length - 1;
                int sum = -nums[i];
                while (lo < hi) {
                    if (nums[lo] + nums[hi] == sum) {
                        result.add(Arrays.asList(nums[i], nums[lo], nums[hi]));
                        while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
                        while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
                        lo++;
                        hi--;
                    } else if (nums[lo] + nums[hi] < sum) {
                        lo++;
                    } else {
                        hi--;
                    }
                }
            }
        }
        return result;
    }


    // 暴力求解，未去重
    public List<List<Integer>> threeSum_01(int[] nums) {
        // 不够三个数，直接返回
        if (nums.length < 3) {
            return new ArrayList<>();
        }
        List<List<Integer>> result = new ArrayList<>();
        for (int i = 0; i < nums.length - 2; i++) {
            for (int j = i + 1; j < nums.length - 1; j++) {
                for (int k = j + 1; k < nums.length; k++) {
                    if (nums[i] + nums[j] + nums[k] == 0) {
                        ArrayList<Integer> add = new ArrayList<>();
                        add.add(nums[i]);
                        add.add(nums[j]);
                        add.add(nums[k]);
                        result.add(add);
                    }
                }
            }
        }
        return result;
    }
}
